package com.lu.utils;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

/**
 * 类名称：JacksonUtil
 * 类描述：
 * 修改备注：
 * @version
 */
public class JacksonUtils {
    /**
     * 方法描述：对象序列化成json
     * 创建时间：2012-11-5
     * 创建人：xujinbiao
     * @param o
     * @return
     */
    public static String writeValueAsString(Object o) {
        ObjectMapper mapper = new ObjectMapper();
        String result = "";
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        mapper.getSerializationConfig().setDateFormat(formatter);
        try {
            result = mapper.writeValueAsString(o);
        } catch (JsonGenerationException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 方法描述：对象带日期格式列化成json
     * 创建时间：2012-11-5
     * 创建人：xujinbiao
     * @param o
     * @param formatter
     * @return
     */
    public static String writeValueAsStringWithDateFormat(Object o, DateFormat formatter) {
        ObjectMapper mapper = new ObjectMapper();
        String result = "";
        mapper.getSerializationConfig().setDateFormat(formatter);
        try {
            result = mapper.writeValueAsString(o);
        } catch (JsonGenerationException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
    

    /**
     * 方法描述：json反序列化成对象
     * 创建时间：2012-11-5
     * 创建人：xujinbiao
     * @param json
     * @param valueType
     * @return
     * @throws JsonParseException
     * @throws JsonMappingException
     * @throws IOException
     */
    public static <T> T readValue(String json, Class<T> valueType) throws JsonParseException, JsonMappingException,
            IOException {
        ObjectMapper mapper = new ObjectMapper();
        return mapper.readValue(json, valueType);
    }

}
